package com.base.widget;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;



public class BackgroundDrawableSpan extends ImageSpan {
    private int mTextSize;
    private int mTextColor;
    private int mPadding;

    public BackgroundDrawableSpan(Drawable drawable, String text, int textSize, int textColor, int padding) {
        super(drawable);
        mTextSize = textSize;
        mTextColor = textColor;
        mPadding = padding;
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        drawable.setBounds(0, 0, ((int) paint.measureText(text)) + 2 * padding, textSize + 2 * padding);
    }

    /**
     * see detail message in android.text.TextLine
     *
     * @param canvas the canvas, can be null if not rendering
     * @param text the text to be draw
     * @param start the text start position
     * @param end the text end position
     * @param x the edge of the replacement closest to the leading margin
     * @param top the top of the line
     * @param y the baseline
     * @param bottom the bottom of the line
     * @param paint the work paint
     */
    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        Drawable drawable = getDrawable();
        canvas.save();
        Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
        float fontHeight = fmPaint.descent - fmPaint.ascent;
        float centerY = y + fmPaint.descent - fontHeight / 2;
        float transY = centerY - (drawable.getBounds().bottom - drawable.getBounds().top) / 2;
        canvas.translate(x, transY);
        drawable.draw(canvas);

        paint.setColor(mTextColor);
        paint.setTextSize(mTextSize);
        Paint.FontMetricsInt fmi = paint.getFontMetricsInt();
        float baseline = centerY - (fmi.bottom - fmi.top) / 2 - fmi.top - transY;
        canvas.drawText(text.subSequence(start, end).toString(), mPadding, baseline, paint);

        canvas.restore();
    }

}
